#include "Timer.hpp"

SimpleTimer::SimpleTimer()
{
    timerThread=nullptr;
    timerSec=std::chrono::seconds(1);
    timerStatus.store(false);
}

SimpleTimer::~SimpleTimer()
{
    timerStatus=false;
    if(timerThread!=nullptr && timerThread->joinable())
        timerThread->join();
}

void SimpleTimer::SetTime(std::chrono::seconds sec)
{
    timerSec=sec;
}

void SimpleTimer::Start()
{
    timerStatus.store(true);
    timerThread=new std::thread(Runnable(this));
}

void SimpleTimer::Stop()
{
    if(timerThread!=nullptr && timerThread->joinable())
        timerThread->join();
    delete timerThread;
    timerThread=nullptr;
}

void SimpleTimer::SetTask(std::function<void()> task)
{
    timerTask=task;
}

SimpleTimer::Runnable::Runnable(SimpleTimer* _controlObject) : controlObject(_controlObject)
{}

SimpleTimer::Runnable& SimpleTimer::Runnable::operator() ()
{
    while (true)
    {
        std::this_thread::sleep_for(controlObject->timerSec);
        if(!controlObject->timerStatus.load()) //防止事件在停止后又执行一次
            break;
        controlObject->timerTask();
    }
    return *this;
}